package info.webest.reminder.contacts;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import info.webest.reminder.R;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;

public class ContactPhoto {
	private static Bitmap bmpDefault = null;

	public ContactPhoto(Context context) {
		createDefaultBitmap(context);
	}

	public static void createDefaultBitmap(Context context) {
		Log.v("createDefaultBitmap", "@@@ --");
		// create default photo
		bmpDefault = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.default_photo);
		bmpDefault = Bitmap.createScaledBitmap(bmpDefault, 96, 96, false);
		// Log.d("create default photo", "@@@ ----  create default photo ");
	}

	public static Bitmap getDefaultBitmap() {
		return bmpDefault;
	}

	public static Bitmap getContactBitmap(Context context, int contact_id, String comment) {

		Uri contactUri = null;
		Bitmap bmp = null;

		
		  Uri person = ContentUris.withAppendedId(
		  ContactsContract.Contacts.CONTENT_URI, contact_id);
		  
		  contactUri = Uri.withAppendedPath(person,
				  ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
		  
		  
/*
		contactUri = Uri.withAppendedPath(
				ContactsContract.Contacts.CONTENT_URI,
				String.valueOf(contact_id));
*/				

		if (contactUri == null)
			return null;

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			
			/*
			try {				
				bmp = MediaStore.Images.Media.getBitmap(
						context.getContentResolver(), contactUri);
				// sb.append("\n Image in Bitmap:" + bitmap);
				// System.out.println(bitmap);

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			*/
			bmp = getByteContactPhoto(context, contact_id);

		} else {
			InputStream photo_stream = null;			
			try {
				photo_stream = context.getContentResolver().openInputStream(
						contactUri);
			} catch (FileNotFoundException e) {				
				e.printStackTrace();
				Log.e("ERROR openInputStream", "@@@ -- id:" + contact_id + ", " + comment);
				return null;
			}
			
			
			/*
			try {
			photo_stream = ContactsContract.Contacts
			  .openContactPhotoInputStream(context.getContentResolver(),
					  contactUri);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//return null;
			}
			*/
			 
			BufferedInputStream buf = new BufferedInputStream(photo_stream);
			bmp = BitmapFactory.decodeStream(buf);
		}
		if (bmp != null)
			Log.v("getContactBitmap", "@@@ -- id:" + contact_id + ", width:"
					+ bmp.getWidth());

		return bmp;
	}

	/*
	 * private String getPathFromURI(Uri contentUri) {
	 * 
	 * if (contentUri == null) return null; ContentResolver resolver =
	 * mActivity.getContentResolver();
	 * 
	 * Cursor cursor; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
	 * // read document_id first (due to KitKat Gallery response // changes)
	 * cursor = resolver.query(uri, null, null, null, null);
	 * cursor.moveToFirst(); String imageId = null; try { imageId =
	 * cursor.getString(cursor .getColumnIndexOrThrow("document_id")); } catch
	 * (Exception e) { // column not found. cursor = queryMediaData(contentUri,
	 * resolver); }
	 * 
	 * if (imageId != null) { imageId =
	 * imageId.substring(imageId.lastIndexOf(":") + 1); cursor.close();
	 * 
	 * cursor = resolver
	 * .query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
	 * null, MediaStore.Images.Media._ID + " = ? ", new String[] { imageId },
	 * null); } } else { cursor = queryMediaData(contentUri, resolver); }
	 * 
	 * if (cursor == null) return null; // added for fixing issue #5512 int
	 * pathColumnIndex = cursor
	 * .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	 * cursor.moveToFirst(); String path = cursor.getString(pathColumnIndex);
	 * cursor.close();
	 * 
	 * return path; }
	 * 
	 * private Cursor queryMediaData(Uri contentUri, ContentResolver resolver) {
	 * Cursor cursor; String[] proj = { MediaStore.Images.Media.DATA }; cursor =
	 * resolver.query(contentUri, proj, null, null, null); return cursor; }
	 */

	/*
	public static Bitmap getByteContactPhoto(Context context, int contactId) {
		Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
				contactId);
		Uri photoUri = Uri.withAppendedPath(contactUri,
				Contacts.Photo.CONTENT_DIRECTORY);
		Cursor cursor = context.getContentResolver().query(photoUri,
				new String[] { Contacts.Photo.PHOTO_URI}, null, null, null);
		cursor.getPosition();
		try {
			//PHOTO_ID - no
			//PHOTO_FILE_ID - no 
			//PHOTO_URI
			//int idIdx = cursor.getColumnIndexOrThrow(Contacts.Photo.PHOTO_URI);
			//DATA15
			//Log.d("CURSOR", "" + cursor.getPosition());
			if (cursor != null) {

				//Log.d("CURSOR.MOVETOFIRST", "" + cursor.moveToNext());

				do {
					Log.d("dintre del while", "" + cursor);
					byte[] data = cursor.getBlob(0);
					if (data != null) {
						Log.d("Dintre del If", "BITMAP");
						return BitmapFactory
								.decodeStream(new ByteArrayInputStream(data));
					}
				} while (cursor.moveToNext());
			}

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		cursor.close();
		return null;
	}
	
	*/
	
	public static Bitmap getByteContactPhoto(Context context, int contactId) {
		Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
		Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
		Cursor cursor = context.getContentResolver().query(photoUri,
		                new String[] {Contacts.Photo.DATA15}, null, null, null);
		if (cursor == null) {
		    return null;
		}
		try {
		    if (cursor.moveToFirst()) {
		        byte[] data = cursor.getBlob(0);
		        if (data != null) {
		            return BitmapFactory.decodeStream( new ByteArrayInputStream(data));
		        }
		    }
		} finally {
		    cursor.close();
		}

		return null;
		}	
}
